package com.luo.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 功能：上传商品图片
 * 作者：Luo。
 * 日期：2024/1/14 12:21
 */
@WebServlet("/addGood")
@MultipartConfig
public class AddGoodController extends HttpServlet {
    @Override
    protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                // 获取webapp目录的绝对路径
                String webAppPath = getServletContext().getRealPath("/");

                // Create a factory for disk-based file items
                DiskFileItemFactory factory = new DiskFileItemFactory();

                // Set the directory used to temporarily store files
                // File uploadDir = new File(getServletContext().getRealPath("/uploads"));
                File uploadDir = new File(webAppPath + File.separator + "imgs");
                factory.setRepository(uploadDir);

                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);

                // Parse the request to get file items
                List<FileItem> fileItems = upload.parseRequest(request);

                // Process the uploaded file items
                for (FileItem fileItem : fileItems) {
                    if (!fileItem.isFormField()) {
                        // This is a file item, handle it
                        String fileName = new File(fileItem.getName()).getName();
                        String filePath = uploadDir + File.separator + fileName;
                        fileItem.write(new File(filePath));

                        // Further processing, e.g., save the file path to a database
                    }
                }

                response.getWriter().write("File uploaded successfully!");
            } catch (FileUploadException e) {
                e.printStackTrace();
                response.getWriter().write("File upload failed.");
            } catch (Exception e) {
                e.printStackTrace();
                response.getWriter().write("Exception occurred: " + e.getMessage());
            }
        } else {
            response.getWriter().write("Request does not contain any file.");
        }
    }
}
